package mdt.action;

import mdt.program.Displayer;
import mdt.program.GraphManager;
import mdt.program.GraphManager.GraphInfo;
import org.tigris.gef.base.Globals;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by xiaobyu on 7/21/2016.
 */
public class ExitAction extends AbstractAction{

    public ExitAction() {
        super("Exit");
        putValue(Action.SMALL_ICON, new ImageIcon(FontBoldAction.class.getResource("/resources/exit-16.png")));
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Globals.showStatus("Quiting...");


        List<GraphInfo> dirtyGraphs = new ArrayList<>();
        for (GraphInfo info : GraphManager.getGraphInfos()) {
            if (info.isDirty()) {
                dirtyGraphs.add(info);
            }
        }

        if (dirtyGraphs.size() > 0) {
            int option = JOptionPane.showConfirmDialog(Displayer.instance().getJFrame(), "There are unsaved changes, save changes?",
                    "Save changes?", JOptionPane.YES_NO_CANCEL_OPTION);
            switch(option) {
                case JOptionPane.YES_OPTION:
                    if (!saveGraphs(dirtyGraphs)) {
                        return;
                    }
                    break;
                case JOptionPane.CANCEL_OPTION:
                    return;
                case JOptionPane.NO_OPTION:
                    break;
            }
        }

        Displayer.instance().getJFrame().dispose();
        System.exit(0);
    }

    // return true if all graphs are confirmed closed either after saving changes or discard changes.
    public boolean saveGraphs(List<GraphInfo> list) {
        SaveAction saveAction = new SaveAction();
        for (GraphInfo info : list) {
            saveAction.actionPerformed(new ActionEvent(info, ActionEvent.ACTION_PERFORMED, "Save"));
            if (info.isDirty()) { //save process terminated due to a canceled save operation
                return false;
            } else {
                GraphManager.removeGraph(info.graph);
            }
        }
        return true;
    }
}
